package app.caihan.scframe.common.loadinghelper

import android.annotation.SuppressLint
import android.app.Activity
import android.view.*
import androidx.annotation.ColorRes
import androidx.appcompat.widget.Toolbar
import app.caihan.scframe.R
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ColorUtils

/**
 * 带behavior效果的ToolBar封装
 *
 * @author Seven-C
 * @date 2020/8/3
 */
class BaseToolbarAdapter(private val config: ToolbarConfig) : LoadingHelper.DecorAdapter() {

    @SuppressLint("InflateParams")
    override fun onCreateDecorView(inflater: LayoutInflater): View {
        val view: View = inflater.inflate(R.layout.scframe_activity_toolbar, null)
        val activity = inflater.context as Activity
        val toolbar: Toolbar = view.findViewById(R.id.baseTitleToolbar)
        if (config.title.isNotEmpty()) {
            toolbar.title = config.title
        }
        if (config.navIconType === NavIconType.BACK) {
//            toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black)
            toolbar.setNavigationOnClickListener { v: View? ->
                if (config.onBackClick != null) {
                    config.onBackClick.invoke()
                } else {
                    activity.finish()
                }
            }
        } else {
            toolbar.navigationIcon = null
        }
        if (config.menuId > 0 && config.onMenuItemClick != null) {
            toolbar.inflateMenu(config.menuId)
            toolbar.setOnMenuItemClickListener { item: MenuItem ->
                config.onMenuItemClick.invoke(item)
            }
        }
        val viewStub: ViewStub = if (config.isSupportScroll) {
            view.findViewById(R.id.baseTitleStubScroll)
        } else {
            view.findViewById(R.id.baseTitleStubNoScroll)
        }
        viewStub.visibility = View.VISIBLE
        setStatusBarStyle(activity, toolbar)
        return view
    }

    override fun getContentParent(decorView: View): ViewGroup {
        return decorView.findViewById(R.id.scframe_base_content_view)
    }

    private fun setStatusBarStyle(activity: Activity, toolbar: Toolbar) {
        setStatusBarLightMode(activity, config.isLightMode)
        setStatusBarColor(activity, toolbar, config.statusBarColor)
    }

    private fun setStatusBarLightMode(activity: Activity, isDarkFont: Boolean) {
        //isLightMode true=状态栏黑色字体,false=状态栏白色字体(系统默认)
        val isLightMode = BarUtils.isStatusBarLightMode(activity)
        if (isLightMode != isDarkFont) {
            BarUtils.setStatusBarLightMode(activity, isDarkFont)
        }
    }

    private fun setStatusBarColor(
        activity: Activity,
        toolbar: Toolbar,
        @ColorRes statusBarColor: Int
    ) {
        BarUtils.setStatusBarColor(activity, ColorUtils.getColor(statusBarColor))
        BarUtils.addMarginTopEqualStatusBarHeight(toolbar)
    }
}
